/**
 * 矩阵
 */
class Mat{

    constructor(v) {
        this.v=v;
    }
    /**
     * 行
     */
    m() {
        return this.v.length;
    }
    /**
     * 列
     */
    n() {
        return this.v[0].length;
    }

    static add(m1,m2){
        let a=m1.v;
        let b=m2.v;
        if (a.length !== b.length || a[0].length !== b[0].length) return null;
        let c= a.map((row, i) => row.map((n, j) => n + b[i][j]));
        return new Mat(c);
    }

    static mul(m1,m2){
        let a=m1.v;
        let b=m2.v;
        if (m1.n() !== m2.m()) {
            throw "矩阵形状不匹配";
        }
        var result = [];
        for (var i = 0; i< a.length; i++) {
            result[i] = [];
            for (var j = 0; j< b[0].length; j++) {
                var sum = 0;
                for (var k = 0; k< b.length; k++) {
                    sum += a[i][k] * b[k][j];
                }
                result[i][j] = sum;
            }
        }
        return new Mat(result);
    }

    //转置
    get T() {
        const arr = new Array(this.n());
        for (let i = 0; i < this.n(); i++) {
            arr[i] = new Array(this.m());
            for (let j = 0; j < this.m(); j++) {
                arr[i][j] = this.v[j][i];
            }
        }
        return new Mat(arr);
    }

    clone() {
        const arr = new Array(this.v);
        for (let i = 0; i < this.m(); i++) {
            arr[i] = new Array(this.n);
            for (let j = 0; j < this.n(); j++) {
                arr[i][j] = this.v[i][j];
            }
        }
        return new Mat(arr);
    }
}


window.Mat=Mat;
